from pydantic import BaseModel, Field
from models import StudentPydanticIn, Student, ClasPydantic, Course, CoursePydantic, TeacherPydantic
from tortoise.transactions import atomic, in_transaction


class StudentSchema(StudentPydanticIn):
    clas_id: int
    pwd: str = 'FW249746'
    courses: list[int] = []
    
    @atomic()
    async def create(self):
        data = self.model_dump()
        courses = data.pop(
            'courses', []
        )
        # 一下操作添加tortoise-orm事务
        # async with in_transaction():
        #     student = await Student.create(**data)
        #     # courses = await Course.filter(id__in=courses)
        #     await student.courses.add(*courses)
        student = await Student.create(**data)
        # courses = await Course.filter(id__in=courses)
        await student.courses.add(*courses)
        return student


class ClasSchema(ClasPydantic):
    pass


class TeacherSchema(TeacherPydantic):
    pass

class CourseSchema(CoursePydantic):
    teacher: TeacherSchema


class StudentListSchema(StudentPydanticIn):
    clas: ClasSchema
    courses: list[CourseSchema]
    